﻿using ManagementApi.Models.Person;
using ManagementApi.Models;
using Modules;
using Modules.Person;
using PmSoft;
using AutoMapper;
using static Modules.Person.PersonConstants;
using PmSoft.Exceptions;
using ManagementApi.Mvc;
using PmSoft.FileStorage;
using Modules.Base;
using Modules.FaceScan;
using Modules.FaceScan.Entitys;
using ManagementApi.Mvc.ApplicationContexts;

namespace ManagementApi.Services
{
    /// <summary>
    /// 人员-公共类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class PublicPersonService
    {
        private readonly PersonService personService;
        private readonly CardReaderService cardReaderService;
        private readonly IFileStorage fileStorage;
        private readonly IMapper mapper;
        private readonly ManagementApplicationContext applicationContext;
        private readonly FacePhotoService personFaceService;
        public PublicPersonService(IMapper mapper, PersonService personService, CardReaderService cardReaderService, ManagementApplicationContext applicationContext, IFileStorage fileStorage, FacePhotoService personFaceService)
        {
            this.personService = personService;
            this.cardReaderService = cardReaderService;
            this.mapper = mapper;
            this.applicationContext = applicationContext;
            this.fileStorage = fileStorage;
            this.personFaceService = personFaceService;
        }

        /// <summary>
        /// 保存人员信息
        /// </summary>
        /// <param name="personCreateForm"></param>
        /// <returns></returns>
        public int SavePersonReadCard(PersonCreateForm personCreateForm)
        {
            try
            {
                applicationContext.Transaction.Begin();//开始事务

                CardInfo cardInfo = cardReaderService.GetCardInfo(personCreateForm.token);
                PersonEditForm form = new PersonEditForm();
                mapper.Map(personCreateForm, form);
                form.Name = cardInfo.Name;
                form.CardNumber = cardInfo.ID;
                form.Gender = Convert.ToByte(cardInfo.Sex);
                form.Birthday = Convert.ToDateTime(cardInfo.Birth);
                form.CardOrg = cardInfo.Company;
                form.CardStartdate = cardInfo.GetBeginDate();
                form.CardEnddate = cardInfo.GetEndDate();
                form.Nation = ((民族)Convert.ToInt32(cardInfo.Race)).GetDescription();
                form.Address = cardInfo.Address;
                PersonInfo? person = personService.GetPersonByCardNo(cardInfo.ID);
                if (person == null)
                {
                    person = new();
                    person.CreateTime = DateTime.Now;
                    mapper.Map(form, person);
                    personService.CreatePersonInfo(person);
                }
                else
                {
                    form.PersonId = person.PersonId;
                    mapper.Map(form, person);
                    personService.UpdatePersonInfo(person);
                }


                //写入数据库person_face表
                FacePhoto? personFace = personFaceService.GetPersonFaceByIdCard(cardInfo.ID);
                string objectName = $"{cardInfo.ID}/idCard_V1.jpg";
                if (personFace == null)
                {
                    personFace = new FacePhoto()
                    {
                        PhotoType = PhotoType.Person,
                        IdCard = cardInfo.ID,
                        IdCardPhotover = 1,
                        IdCardPhoto = objectName,
                        IdCardPhotoTime = DateTime.Now,
                        CreateTime = DateTime.Now
                    };
                    personFaceService.Insert(personFace);
                }
                else
                {
                    personFace.IdCardPhotover = personFace.IdCardPhotover + 1;
                    objectName = $"{cardInfo.ID}/idCard_V{personFace.IdCardPhotover}.jpg";
                    personFace.IdCardPhoto = objectName;
                    personFace.IdCardPhotoTime = DateTime.Now;
                    personFaceService.Update(personFace);
                }

                //上传到minio
                byte[] picData = Convert.FromBase64String(cardInfo.HeadPic);
                fileStorage.PutFileAsync(FileBuckets.Person, objectName, picData).GetAwaiter().GetResult();

                applicationContext.Transaction.Complete();//完成事务
                return person.PersonId;
            }
            catch (BusinessException ex) {
                applicationContext.Transaction.Abort();//回滚事务
                throw new BusinessException(ex.Message);
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();//回滚事务
                throw new BusinessException("写入用户数据失败");
            }
        }

    }
}
